package com.cai.mr.lib.utils;

import android.os.Bundle;
import android.text.TextUtils;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * Created by hai8108 on 16/2/5.
 */
public class OkHttpUtil {
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    static{
        mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    }
    /**
     * 该不会开启异步线程。
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return mOkHttpClient.newCall(request).execute();
    }
    /**
     * 开启异步线程访问网络
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback){
        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }
    /**
     * 开启异步线程访问网络, 且不在意返回结果（实现空callback）
     * @param request
     */
    public static void enqueue(Request request){
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response arg0) throws IOException {
            }
            @Override
            public void onFailure(Request arg0, IOException arg1) {
            }
        });
    }

    /**
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String getStringFromServer(String url) throws IOException{
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseString = response.body().string();
            LogInfo.log("httpApi", "response = "+responseString);
            return responseString;
        } else {
            LogInfo.log("httpApi", "response.message() = "+response.message());
            throw new IOException(response.message());
        }
    }

    /**
     *
     * @param url
     * @param responseCallback
     * @throws IOException
     */
    public static void getStringFromServer(String url, Callback responseCallback) throws
            IOException{
        Request request = new Request.Builder().url(url).build();
        enqueue(request, responseCallback);
    }
    /**
     *  为HttpGet 的 url 方便的添加多个name value 参数。
     * @param baseUrl
     * @param params
     * @param endUrl
     * @return
     */
    public static String attachHttpGetParams(String baseUrl, Bundle params, String endUrl){
        return encodeUrl(baseUrl, params, endUrl);
    }
    private static String encodeUrl(String baseUrl, Bundle params, String endUrl) {
        StringBuilder sb = new StringBuilder();
        if (params == null) {
            return null ;
        }
        boolean first = true;
        sb.append(baseUrl);
        for (String key : params.keySet()) {
            if (first) {
                sb.append("?");//GET
                first = false;
            } else {
                sb.append("&");
            }
            String pa = params.getString(key);
            if(pa != null){
                sb.append(key + "=" + URLEncoder.encode(pa));
            }else{
                sb.append(key + "=");
            }
        }
        if(!TextUtils.isEmpty(endUrl)){
            sb.append(endUrl);
        }
        return sb.toString();
    }
}
